
import csv
from mailing import send_mail_cse_smtp
from checksum import write_checksum


def gen_link_mail(addresses):
    link_mail = []
    for adr in addresses:
        if len(adr) == 10 and adr[:4] == "1155":
            link_mail.append(adr + "@link.cuhk.edu.hk")
    return link_mail


if __name__ == "__main__":
    from sys import argv
    if len(argv) == 2 and argv[1] == "confirmsend":
        testing = False
    else:
        testing = True
    vers = {}
    vers['1'] = []
    vers['2'] = []
    vers['3'] = []
    vers['4'] = []
    vers['5'] = []
    with open('./info.csv') as f:
        csv_reader = csv.reader(f, delimiter=',')
        line_count = 0
        for row in csv_reader:
            if line_count == 0:
                # print(f'Column names are {", ".join(row)}')
                line_count += 1
            else:
                vers[row[1]].append(row[0])
                line_count += 1

    for ver in vers.keys():
        bcc = gen_link_mail(vers[ver])
        attach = [f'./CSCI3100_Final_Exam/{ver}/CSCI3100_Final_Exam.zip']
        logmsg = f"BCC: {';'.join(bcc)}. File: {';'.join(attach)}"
        cksum = write_checksum(logmsg)
        receiver = ['csci3100@cse.cuhk.edu.hk']
        # receiver = ['tyyang@cse.cuhk.edu.hk']
        subject = "CSCI3100 Final Exam"
        text = f'''Dear student,

Attached is the question set and answer book.

Regards,
CSCI3100 TA Group

'''
        if testing:
            # print(receiver)
            # print(subject)
            print(text)
            print(bcc)
            print(attach)
        else:
            send_mail_cse_smtp('csci3100', subject, text, attach, receiver, bcc)
            print(f'Sent mail to ver {ver}, bccing {bcc}')
